package com.mc.common.guava;


import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.google.common.collect.ImmutableMap.of;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsSame.sameInstance;
import static org.junit.Assert.assertThat;

/**
 * guava 拼接工具类
 */
public class JoinerTest {

    private final List<String> strList = Arrays.asList("CC", "cici", "fmc", "celina");
    private final List<String> strListWithNullValue = Arrays.asList("CC", "cici", "fmc", "celina", null);
    private final Map<String, String> strMap = of("hello", "fmc", "您好", "cc");

    /**
     * 测试拼接
     */
    @Test
    public void joinTest(){
        String result = Joiner.on("#").join(strList);
        assertThat(result, equalTo("CC#cici#fmc#celina"));
    }

    /**
     * 测试空指针
     */
    @Test(expected = NullPointerException.class)
    public void joinTestWithNullValue(){
        String result = Joiner.on("#").join(strList);
        assertThat(result, equalTo("CC#cici#fmc#celina"));
    }

    /**
     * 不取空值
     */
    @Test
    public void joinTestSkipNullValue(){
        String result = Joiner.on("#").skipNulls().join(strListWithNullValue);
        assertThat(result, equalTo("CC#cici#fmc#celina"));
    }

    /**
     * 空值替换成默认值
     */
    @Test
    public void joinTestSkipNullValueUseDefaultValue(){
        String result = Joiner.on("#").useForNull("abc").join(strListWithNullValue);
        assertThat(result, equalTo("CC#cici#fmc#celina#abc"));
    }

    @Test
    public void testJoin_On_Append_To_StringBuilder() {
        final StringBuilder builder = new StringBuilder();
        StringBuilder resultBuilder = Joiner.on("#").useForNull("abc").appendTo(builder, strListWithNullValue);
        assertThat(resultBuilder, sameInstance(builder));
        assertThat(resultBuilder.toString(), equalTo("CC#cici#fmc#celina#abc"));
        assertThat(builder.toString(), equalTo("CC#cici#fmc#celina#abc"));
    }

    @Test
    public void testJoinOnWithMap() {
        assertThat(Joiner.on('#').withKeyValueSeparator("=").join(strMap), equalTo("Hello=Guava#Java=Scala"));
    }
    @Test
    public void testJoinOToMap() {
        final Map<String, String> join = Splitter.on("&").withKeyValueSeparator("=").split("id=123&name=green");
    }
}
